import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from 'axios'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref({
    id: '',
    name: '管理员',
    email: '',
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    role: 'admin',
    permissions: []
  })
  const isLoggedIn = computed(() => !!token.value)

  // 登录
  const login = async (loginForm) => {
    try {
      // 模拟登录API调用
      const response = await axios.post('/api/auth/login', loginForm)
      const { token: newToken, user } = response.data
      
      token.value = newToken
      userInfo.value = user
      localStorage.setItem('token', newToken)
      
      // 设置axios默认header
      axios.defaults.headers.common['Authorization'] = `Bearer ${newToken}`
      
      return { success: true }
    } catch (error) {
      console.error('登录失败:', error)
      return { success: false, message: error.response?.data?.message || '登录失败' }
    }
  }

  // 退出登录
  const logout = () => {
    token.value = ''
    userInfo.value = {
      id: '',
      name: '',
      email: '',
      avatar: '',
      role: '',
      permissions: []
    }
    localStorage.removeItem('token')
    delete axios.defaults.headers.common['Authorization']
  }

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const response = await axios.get('/api/user/info')
      userInfo.value = response.data
      return response.data
    } catch (error) {
      console.error('获取用户信息失败:', error)
      logout()
      throw error
    }
  }

  // 检查权限
  const hasPermission = (permission) => {
    if (userInfo.value.role === 'admin') return true
    return userInfo.value.permissions.includes(permission)
  }

  // 检查角色
  const hasRole = (role) => {
    return userInfo.value.role === role
  }

  // 初始化
  const init = () => {
    if (token.value) {
      axios.defaults.headers.common['Authorization'] = `Bearer ${token.value}`
      // 可以在这里获取用户信息
      // getUserInfo()
    }
  }

  return {
    // 状态
    token,
    userInfo,
    isLoggedIn,
    
    // 方法
    login,
    logout,
    getUserInfo,
    hasPermission,
    hasRole,
    init
  }
})